package com.vip8.recorder.service.utils;


import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.Signature;
import org.aspectj.lang.reflect.MethodSignature;

public class AopUtil {

    /**
     * 获取方法签名
     *
     * @param joinPoint
     * @return
     */
    public static MethodSignature getMethodSignature(ProceedingJoinPoint joinPoint) {
        Signature signature = joinPoint.getSignature();
        if (signature instanceof MethodSignature) {
            return (MethodSignature) signature;
        }
        return null;
    }

    /**
     * 获取执行的方法名
     *
     * @param joinPoint
     * @return
     */
    public static String getMethodName(ProceedingJoinPoint joinPoint) {
        MethodSignature methodSignature = getMethodSignature(joinPoint);
        if (methodSignature == null) {
            return null;
        }
        Object object = joinPoint.getTarget();
        String className = object.getClass().getSimpleName();
        StringBuilder builder = new StringBuilder();
        builder.append(className)
                .append(".")
                .append(methodSignature.getName());
        return builder.toString();
    }

    /**
     * 获取堆栈信息
     *
     * @param throwable
     * @return
     */
    public static String getStaceTrace(Throwable throwable) {

        if (throwable == null) {
            return "";
        }

        StringBuffer sb = new StringBuffer();
        StackTraceElement[] stackArray = throwable.getStackTrace();
        for (int i = 0; i < stackArray.length; ++i) {
            StackTraceElement element = stackArray[i];
            sb.append("\n")
                    .append(element.getClassName())
                    .append(".").append(element.getMethodName())
                    .append("(").append(element.getFileName())
                    .append(":").append(element.getLineNumber()).append(")")
                    .append("\n");
        }
        return sb.toString();


    }
}
